import React, {useState,useEffect,useRef} from 'react'
import {
  Row,
  Col,
  Flex,
  Typography,
  Button,
  Form,
  Input,
  Radio,
  Select,
  message
} from 'antd'
import Amap from '../components/Amap'
import ManyUpload from '../components/ManyUpload'
import ImageIdUpload from '../components/ImageIdUpload'
import {sellerVerifyList} from '../service/seller'
import {useNavigate, useParams} from 'react-router-dom'
import {
  cityListAPI,
  provinceListAPI,
  shopAdd,
  shopDetail,
  shopEdit
} from '../service/shop'

export default function ShopAdd() {
  const navigate = useNavigate()
  // 商家id
  const [sellerId, setSellerId] = useState()
  // 获取传递的id
  const {id} = useParams()
  const isEditing = id !== undefined // 根据id是否存在判断是编辑还是添加
  // 商家列表
  const [sellerList, setSellerList] = useState([])
  // 保存所有省份
  const [provinceList, setProvinceList] = useState([])
  // 保存省份ID
  const [provinceId, setProvinceId] = useState()
  // 保存所有城市
  const [cityList, setCityList] = useState([])
  // 保存城市ID
  const [cityId, setCityId] = useState()
  // 保存所有区域
  const [districtList, setDistrictList] = useState([])
  // 保存区域ID
  const [districtId, setDistrictId] = useState()
  // 保存Logo
  const [imageLogo, setImageLogo] = useState()
  const [imageId, setImageId] = useState()
  // 图片列表
  const [fileList, setFileList] = useState([])
  const [form] = Form.useForm()

  const [gdmap, setGDMap] = useState()

  //引入高德地图
  // 存储经纬度的状态
  const [coordinates, setCoordinates] = useState({
    longitude: '',
    latitude: ''
  });
  const [position, setPosition] = useState({
    storeLongitude: 1186.397428,
    storeLatitude: 39.90923
  })
  // 地图容器和地图实例的引用
  const mapContainer = useRef(null);
  const mapInstance = useRef(null);
  // 高德地图API密钥，需要用户自行申请
  const AMAP_KEY = '301a49b4c20f91f5de4389f4a6e51c9b'; // 请替换为您自己的API密钥
  // 加载高德地图脚本
  useEffect(() => {
    const loadMapScript = () => {
      return new Promise((resolve, reject) => {
        // 检查脚本是否已加载
        if (window.AMap) {
          resolve(window.AMap);
          return;
        }

        // 创建script标签加载地图API
        const script = document.createElement('script');
        script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}`;
        script.type = 'text/javascript';
        script.onload = () => {
          if (window.AMap) {
            resolve(window.AMap);
          } else {
            reject(new Error('高德地图API加载失败'));
          }
        };
        script.onerror = () => reject(new Error('高德地图API加载失败'));
        document.head.appendChild(script);
      });
    };

    // 加载脚本并初始化地图
    loadMapScript().then(AMap => {
      if (mapContainer.current && !mapInstance.current) {
        // 初始化地图实例
        mapInstance.current = new AMap.Map(mapContainer.current, {
          zoom: 13, // 初始缩放级别
          center: [116.397428, 39.90923], // 初始中心点坐标（北京）
          resizeEnable: true // 允许地图自适应容器大小变化
        });

        // 添加地图点击事件
        mapInstance.current.on('click', (e) => {
          const {lng, lat} = e.lnglat;
          // 更新经纬度状态，保留6位小数
          setCoordinates({
            longitude: lng.toFixed(6),
            latitude: lat.toFixed(6)
          });
        });
      }
    }).catch(error => {
      console.error('地图初始化失败:', error);
    });
    // 组件卸载时清理
    return () => {
      if (mapInstance.current) {
        mapInstance.current.destroy();
        mapInstance.current = null;
      }
    };
  }, [AMAP_KEY]);
  // 处理输入框变化
  const handleInputChange = (e) => {
    const {name, value} = e.target;
    setCoordinates(prev => ({
      ...prev,
      [name]: value
    }));
  };
  useEffect(() => {
    ;(async () => {
      // 获取商家列表
      const res = await sellerVerifyList({pageSize: 200})
      console.log(res)
      if (res.data) {
        setSellerList(res.data.objects)
      }
      // 获取所有省份
      const res2 = await provinceListAPI()
      //console.log(res2)
      setProvinceList(res2.data)
    })()

    // 判断是编辑还是新增
    if (isEditing) {
      ;(async () => {
        const res = await shopDetail(id)
        console.log(res.data)
        // 设置地图的坐标
        setCoordinates({
          longitude: res.data.storeLongitude,
          latitude: res.data.storeLatitude
        });
        if(res.data.provinceId!=null){
          // 通过省份查询城市列表
          const res2 = await cityListAPI(res.data.provinceId)
          // 保存城市
          setCityList(res2.data)
          // 通过城市获取地区列表
          const res3 = await cityListAPI(res.data.cityId)
          setDistrictList(res3.data)
        }


        form.setFieldsValue({
          ...res.data
        })
        // setSellerId(res.data.sellerId)
        // 设置logo
        if(res.data.storeLogo!=null){
          setImageLogo(res.data.storeLogo)
        }
        // 设置图片列表
        if(res.data.pictureVOS!=null){

          setFileList(
              res.data.pictureVOS.map((item) => {
                return {
                  id: item.id,
                  url: item.image
                }
              })
          )
        }
      })()
    }

  }, [])
  useEffect(() => {
    //默认的经纬度
    setCoordinates({
      longitude: 116.397,
      latitude: 39.919412
    });
  }, [position.storeLongitude])

  return (
      <>
        <Row className="info">
          <Col span={24}>
            <Flex justify={'space-between'}>
              <Typography.Title level={3}>信息管理</Typography.Title>
            </Flex>
          </Col>
        </Row>
        <Row className="container">
          <Col span={24}>
            <Typography.Title level={4}>
              {isEditing ? '编辑店铺' : '新增店铺'}
            </Typography.Title>
          </Col>
          <Col span={24}>
            <Form
                form={form}
                labelCol={{
                  span: 2
                }}
                wrapperCol={{
                  span: 16
                }}
                onFinish={async (value) => {
                  const ids = fileList.map((item) => {
                    if (item.response) {
                      return item.response.data.url
                    } else {
                      return item.url
                    }
                  })
                  // console.log(ids)
                  // console.log(value)
                  delete value.zuobiao
                  value.storeLogo = imageLogo
                  value.storeLongitude = coordinates.longitude
                  value.storeLatitude = coordinates.latitude
                  value.storeImagesIds = ids
                  //坐标
                  const values = await form.validateFields();
                  const  zuob = value.zuobiao;
                  // 如果是新增
                  if (!isEditing) {
                    const res = await shopAdd(value)
                    console.log(res)
                    if (res.code === '0') {
                      message.success('新增成功')
                      navigate('/admin/shop/list')
                    } else {
                      message.error('新增失败')
                    }
                  } else {
                    // 如果是编辑
                    const res = await shopEdit({...value, id})
                    if (res.code === '0') {
                      message.success('编辑成功')
                      navigate('/admin/shop/list')
                    } else {
                      message.error('编辑失败')
                    }
                  }
                }}
            >
              <Form.Item
                  label="商家名称"
                  name="businessId"
                  rules={[{required: true, message: '请选择商家'}]}
              >
                <Select
                    placeholder="请选择商家"
                    options={sellerList}
                    fieldNames={{value: 'id', label: 'businessName'}}
                    style={{width: 400}}
                    onChange={(value) => {
                      console.log(value)
                      // setSellerId(value)
                    }}
                />
              </Form.Item>
              <Form.Item
                  label="店铺名称"
                  name="storeName"
                  rules={[{required: true, message: '请输入店铺名称'}]}
              >
                <Input placeholder="请输入店铺名称" style={{width: 400}}/>
              </Form.Item>
              <Form.Item
                  label="店铺电话"
                  name="storePhone"
                  rules={[{required: true, message: '请输入店铺电话'}]}
              >
                <Input placeholder="请输入店铺电话" style={{width: 400}}/>
              </Form.Item>
              <Form.Item
                  label="负责人"
                  name="storeHeadName"
                  rules={[
                    {
                      required: true,
                      message: '负责人不能为空'
                    }
                  ]}
              >
                <Input placeholder="请输入负责人" style={{width: 400}}/>
              </Form.Item>
              <Form.Item
                  label="负责人电话"
                  name="storeHeadPhone"
                  rules={[{required: true, message: '请输入负责人电话'}]}
              >
                <Input placeholder="请输入负责人电话" style={{width: 400}}/>
              </Form.Item>
              <Form.Item label="店铺地区">
                <Row>
                  <Col span={5}>
                    <Form.Item name={'provinceId'}>
                      <Select
                          placeholder="省"
                          style={{width: 150}}
                          onChange={async (value) => {
                            console.log(value)
                            const res = await cityListAPI(value)
                            console.log(res)
                            setCityList(res.data)
                            // 保存省份id
                            setProvinceId(value)
                            setDistrictList([])
                            // 当选择省份后，区域部分还显示之前选中的内容，现在不能有内容显示
                            form.setFieldsValue({
                              areaId: '',
                              cityId: ''
                            })
                          }}
                          options={provinceList}
                          fieldNames={{value: 'id', label: 'name'}}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={5}>
                    <Form.Item name={'cityId'}>
                      <Select
                          placeholder="市"
                          style={{width: 150}}
                          options={cityList}
                          fieldNames={{value: 'id', label: 'name'}}
                          onChange={async (value) => {
                            console.log(value)
                            const res = await cityListAPI(value)
                            console.log(res)
                            setDistrictList(res.data)
                            // 保存市id
                            setCityId(value)
                          }}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={5}>
                    <Form.Item name={'areaId'}>
                      <Select
                          placeholder="区"
                          style={{width: 150}}
                          options={districtList}
                          fieldNames={{value: 'id', label: 'name'}}
                          onChange={(value) => {
                            console.log(value)
                            // 保存区id
                            setDistrictId(value)
                          }}
                      />
                    </Form.Item>
                  </Col>
                </Row>
              </Form.Item>
              <Form.Item
                  label="详细店址"
                  name="storeLocation"
                  rules={[{required: true, message: '请输入详细店址'}]}
              >
                <Input placeholder="请输入详细地址" style={{width: 400}}/>
              </Form.Item>
              <Form.Item label="店铺坐标" name="zuobiao">
                <input
                    type="text"
                    name="longitude"
                    value={coordinates.longitude+","+coordinates.latitude}
                    onChange={handleInputChange}
                    style={{
                      width: '200px',
                      padding: '8px',
                      borderRadius: '4px',
                      border: '1px solid #ddd',
                      fontSize: '14px'
                    }}
                    placeholder="点击地图获取经度"
                />
                <div
                    ref={mapContainer}
                    style={{
                      width: '100%',
                      height: '400px',
                      border: '1px solid #ddd',
                      borderRadius: '4px',
                      marginBottom: '20px'
                    }}
                />

              </Form.Item>
              <Form.Item label="店铺图片">
                <ManyUpload fileList={fileList} setFileList={setFileList}/>
              </Form.Item>
              <Form.Item label="店铺Logo">
                <ImageIdUpload
                    imageUrl={imageLogo}
                    setImageUrl={setImageLogo}
                    imageId={imageId}
                    setImageId={setImageId}
                />
              </Form.Item>
              <Form.Item label="商家简介" name="storeIntroduction">
                <Input.TextArea
                    placeholder="请输入商家简介"
                    style={{width: 400}}
                />
              </Form.Item>
              <Form.Item label="排序" name="sort" initialValue={1}>
                <Select
                    placeholder="请选择店铺状态"
                    style={{width: 400}}
                    options={[
                      {
                        value: 1,
                        label: '升序'
                      },
                      {
                        value: 2,
                        label: '降序'
                      }
                    ]}
                />
              </Form.Item>
              <Form.Item label="营业时间" name="tradeTime">
                <Input placeholder="请输入营业时间" style={{width: 400}}/>
              </Form.Item>
              <Form.Item label="店铺状态" name="storeStatus" initialValue={0}>
                <Radio.Group name="radioGroup">
                  <Radio value={0}>开启</Radio>
                  <Radio value={1}>禁用</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item label=" " colon={false}>
                <Button
                    type="primary"
                    htmlType="submit"
                    style={{marginRight: 10}}
                >
                  确定
                </Button>
                <Button type="default" htmlType="reset">
                  重置
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>
      </>
  )
}
